package com.ymq.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ymq.reggie.common.R;
import com.ymq.reggie.dto.DishDto;
import com.ymq.reggie.entity.Category;
import com.ymq.reggie.entity.Dish;
import com.ymq.reggie.entity.DishFlavor;
import com.ymq.reggie.service.CategoryService;
import com.ymq.reggie.service.DishFlavorService;
import com.ymq.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/dish")
public class DishController {

    @Autowired
    private DishService dishService;
    @Autowired
    private DishFlavorService dishFlavorService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 新增菜品
     * @param dto
     * @return
     */
    @PostMapping()
    public R<String> save(@RequestBody DishDto dto){
        log.info(dto.toString());
        dishService.saveWithflave(dto);
        String dish= "dish_"+dto.getCategoryId()+"*";
        Set keys = redisTemplate.keys(dish);
        redisTemplate.delete(keys);

        return R.success("菜品添加成功");
    }

    /**
     * 菜品分页
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String name){
        Page<Dish> page1 = new Page<>(page,pageSize);


        LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(name!=null, Dish::getName,name);
        wrapper.orderByAsc(Dish::getSort);
        log.info("wrapper:{}",wrapper);

        dishService.page(page1,wrapper);
        Page<DishDto> page2=new Page<>(page,pageSize);
        //对象拷贝
        BeanUtils.copyProperties(page1,page2,"records");
        List<Dish> records = page1.getRecords();

        List<DishDto> list = records.stream().map((item) -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item, dishDto);
            Long categoryId = item.getCategoryId();
            Category category = categoryService.getById(categoryId);
            String name1 = category.getName();
            dishDto.setCategoryName(name1);
            return dishDto;
        }).collect(Collectors.toList());
        page2.setRecords(list);

        return R.success(page2);
    }

    /**
     * 菜品修改
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<DishDto> get(@PathVariable Long id){
        DishDto dishDto = dishService.getById(id);
        return R.success(dishDto);
    }

    /**
     * 保存菜品修改信息
     * redis
     * @param dishDto
     * @return
     */
    @PutMapping()
    public R<String> updateDishWithFlavor(@RequestBody DishDto dishDto){

        dishService.updateDishWithFlavor(dishDto);
        String dish= "dish_"+dishDto.getCategoryId()+"*";
        Set keys = redisTemplate.keys(dish);
        redisTemplate.delete(keys);


        return R.success("菜品修改成功");
    }

    /**
     * 菜品起售
     * @param ids
     * @return
     */
     @PostMapping("/status/{status}")
    public R<String> dishStatus(String ids, @PathVariable int status) {
         log.info("ids:{}", ids);
         log.info("status:{}", status);
         String[] split = ids.split(",");
         for (String s : split) {
             Dish byId = dishService.getById(s);
             byId.setStatus(status);
             dishService.updateById(byId);

         }
         if (status==0){
             return R.success("菜品已下架");

         }

         return R.success("菜品已上架");

     }

    /**
     * 菜品删除
     *
     * @return
     */
    @DeleteMapping
    public R<String> delete( String ids) {

        log.error("123");
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();

        String[] splitId = ids.split(",");

        List<String> list = Arrays.stream(splitId).toList();


        boolean flag = dishService.removeByIds(list);
        if (!flag) {
            return R.error("删除失败");
        }


//        queryWrapper.eq(Dish::getId, ids);
        Set keys = redisTemplate.keys("dish*");
        redisTemplate.delete(keys);



        return R.success("删除成功");
    }

    /**
     * 菜品
     * redis缓存
     * @param dish
     * @return
     */
    @GetMapping("/list")
    public R<List<DishDto>> list(Dish dish){
        List<DishDto> list1;
        String dishKey="dish_"+dish.getCategoryId()+"_"+dish.getStatus();
        //通过分类id查询redis中是否存在
        list1 = (List<DishDto>) redisTemplate.opsForValue().get(dishKey);
        //存在 从redis中取数据
        if(list1!=null){
            log.info("从redis中获取数据");
            return R.success(list1);
        }
        //不存在从数据库中取数据
        log.info("category:{}",dish.getId());
        list1 = dishService.updateRedisDish(dish);

        return R.success(list1);
    }
}
